﻿Option Strict On

Namespace IO

    Public MustInherit Class BinaryAttachment

        Private WithEvents _process As System.Diagnostics.Process

        Public Sub New()
            _DeleteOnExit = True
        End Sub

        Public Property Bezeichnung As String

        Public Property Filename As String

        Public Property Binary As Byte()

        Public MustOverride Property Id As Integer

        Public Property DeleteOnExit As Boolean

        Public Overridable Function CreateTempFile() As String
            Return CreateFile(System.IO.Path.GetTempPath())
        End Function

        Public Overridable Function CreateFile(ByVal path As String) As String

            If Binary Is Nothing Then _
                Throw New NullReferenceException("Binärdatei ist nicht gefüllt.")

            Dim fullDirectory As String = String.Format("{0}kostenuebersicht_attach\{1}\", System.IO.Path.GetTempPath(), Id.ToString())
            Dim fullLocalName As String = _
                String.Format("{0}{1}", _
                              fullDirectory, _
                              Filename)

            If System.IO.File.Exists(fullLocalName) Then _
                System.IO.File.Delete(fullLocalName)

            If Not System.IO.Directory.Exists(fullDirectory) Then _
                System.IO.Directory.CreateDirectory(fullDirectory)


            Dim fs As New System.IO.FileStream(fullLocalName, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write)
            fs.Write(Binary, 0, Binary.Length)
            fs.Close()

            Return fullLocalName

        End Function

        Public Overridable Sub StartAsProcess()

            _process = New Process
            _process.StartInfo.FileName = CreateTempFile()
            _process.Start()

        End Sub

        Private Sub _process_Exited(ByVal sender As Object, ByVal e As System.EventArgs) Handles _process.Exited

            ' TODO: Das funktioniert hier noch nicht.

            If Not _DeleteOnExit Then _
                Exit Sub

            If System.IO.File.Exists(CType(sender, System.Diagnostics.Process).StartInfo.FileName) Then _
                System.IO.File.Delete(CType(sender, System.Diagnostics.Process).StartInfo.FileName)

        End Sub

    End Class

End Namespace